//
//  BookManager.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import Foundation
class BookManager {
    static let standard = BookManager()
    
    let userDefaults = UserDefaults.standard
    let bookDao = KoiAccountingDB.standard.getBookDao()
    var uid: String {
        return KoiAccountingUserManager.standard.userId()
    }
    
    private var mCurrentBook:AccountingBook?
    
    struct BookPref {
        private static let book_pref = "book:"
        static let cache_book = book_pref+"cache:"
    }
    
    func initBook() {
        let book = getCacheBook(uid: uid)
        if (book == nil) {
            // 初始化 book
            mCurrentBook = defaultBook()
            // 保存到缓存中，作为当前选中账本
            saveCacheBook(book:mCurrentBook)
            // 保存到数据库
            DispatchQueue.global(qos: .background).async{
                self.bookDao.save(book:self.mCurrentBook)
            }
        }
    }
    
    func currentBookId() -> String {
        return currentBook().bookId.orEmpty
    }
    
    func currentBook() -> AccountingBook {
        if (mCurrentBook != nil) {
            return mCurrentBook!
        }
        mCurrentBook = getCacheBook(uid: uid)
        if (mCurrentBook == nil) {
            mCurrentBook = defaultBook()
        }
        return mCurrentBook!
    }
    
    func setCurrentBook(book: AccountingBook) {
        mCurrentBook = book
        saveCacheBook(book: book)
    }
    
    func hasDefaultBook(uid: String) -> Bool {
        return bookDao.getBook(uid: uid, bookId: AccountingBook.def_book_id) != nil
    }
    
    private func getCacheBook(uid: String) -> AccountingBook? {
        let jsonStr = userDefaults.string(forKey: BookPref.cache_book+uid).orEmpty
        guard let data = jsonStr.data(using: .utf8) else {
            return nil
        }
        do {
            let book = try JSONDecoder().decode(AccountingBook.self, from: data)
            return book
        } catch {
            return nil
        }
    }
    
    private func saveCacheBook(book: AccountingBook?) {
        do {
            let uid = book?.uid ?? ""
            let jsonData = try JSONEncoder().encode(book)
            let jsonStr = String(data: jsonData, encoding: .utf8)
            userDefaults.set(jsonStr, forKey: BookPref.cache_book+uid)
        } catch {
            logger.error("saveCacheBook \(error)")
        }
    }
    
    func defaultBook() -> AccountingBook {
        let now = Date()
        let createTime = now.toISODateString()
        return AccountingBook(
            bookId: AccountingBook.def_book_id,
            bookName: "默认账本",
            bookColor: "#EF443A",
            uid: uid,
            createTime: createTime,
            updateTime: createTime
        )
    }
    
    func clearDefaultBook () {
        userDefaults.removeObject(forKey: BookPref.cache_book+uid)
        bookDao.deleteBook(uid: uid, bookId: AccountingBook.def_book_id)
    }
}
